"""
AI场景组合模式数据模型
"""

from datetime import datetime
from enum import Enum
from typing import List, Optional

from pydantic import BaseModel, Field, ConfigDict, model_serializer


class SceneStatus(str, Enum):
    """场景状态枚举"""
    ACTIVE = "active"
    INACTIVE = "inactive"
    PENDING_REVIEW = "pending_review"
    ARCHIVED = "archived"


class AIWebScene(BaseModel):
    """AI场景组合模式实体类"""
    model_config = ConfigDict(from_attributes=True)

    scene_id: str = Field(..., description="场景唯一标识")
    scene_name: str = Field(..., max_length=100, description="场景名称")
    description: Optional[str] = Field(None, description="场景描述")
    parent_id: Optional[str] = Field(None, description="父节点ID")
    node_path: Optional[str] = Field(None, max_length=500, description="节点路径，格式：/父ID/子ID/...")
    node_level: int = Field(default=0, description="节点层级，根节点为0")
    sort_order: int = Field(default=0, description="同级节点排序序号")
    scene_status: SceneStatus = Field(default=SceneStatus.ACTIVE, description="场景状态")
    creator: str = Field(..., max_length=50, description="创建人")
    create_time: datetime = Field(..., description="创建时间")
    modifier: Optional[str] = Field(None, max_length=50, description="修改人")
    modify_time: Optional[datetime] = Field(None, description="修改时间")
    version: int = Field(default=0, description="乐观锁版本号")

    # 组合模式相关字段
    children: List['AIWebScene'] = Field(default_factory=list, description="子节点列表")

    @model_serializer
    def serialize_model(self):
        """自定义序列化器"""
        data = self.__dict__.copy()
        if 'create_time' in data and data['create_time']:
            data['create_time'] = data['create_time'].isoformat()
        if 'modify_time' in data and data['modify_time']:
            data['modify_time'] = data['modify_time'].isoformat()
        return data

    def add_child(self, child: 'AIWebScene') -> None:
        """添加子节点"""
        child.parent_id = self.scene_id
        child.node_level = self.node_level + 1
        child.node_path = f"{self.node_path or ''}/{self.scene_id}"
        self.children.append(child)

    def remove_child(self, child_id: str) -> bool:
        """移除子节点"""
        for i, child in enumerate(self.children):
            if child.scene_id == child_id:
                self.children.pop(i)
                return True
        return False

    def find_child(self, child_id: str) -> Optional['AIWebScene']:
        """查找子节点"""
        for child in self.children:
            if child.scene_id == child_id:
                return child
            # 递归查找
            found = child.find_child(child_id)
            if found:
                return found
        return None

    def get_all_descendants(self) -> List['AIWebScene']:
        """获取所有后代节点"""
        descendants = []
        for child in self.children:
            descendants.append(child)
            descendants.extend(child.get_all_descendants())
        return descendants

    def is_leaf(self) -> bool:
        """判断是否为叶子节点"""
        return len(self.children) == 0

    def is_root(self) -> bool:
        """判断是否为根节点"""
        return self.parent_id is None

    def get_depth(self) -> int:
        """获取节点深度"""
        if self.is_leaf():
            return 0
        return max(child.get_depth() for child in self.children) + 1


class AIWebSceneCreate(BaseModel):
    """创建场景请求模型"""
    scene_name: str = Field(..., max_length=100, description="场景名称")
    description: Optional[str] = Field(None, description="场景描述")
    parent_id: Optional[str] = Field(None, description="父节点ID")
    sort_order: int = Field(default=0, description="同级节点排序序号")
    scene_status: SceneStatus = Field(default=SceneStatus.ACTIVE, description="场景状态")
    creator: str = Field(..., max_length=50, description="创建人")


class AIWebSceneUpdate(BaseModel):
    """更新场景请求模型"""
    scene_name: Optional[str] = Field(None, max_length=100, description="场景名称")
    description: Optional[str] = Field(None, description="场景描述")
    parent_id: Optional[str] = Field(None, description="父节点ID")
    sort_order: Optional[int] = Field(None, description="同级节点排序序号")
    scene_status: Optional[SceneStatus] = Field(None, description="场景状态")
    modifier: str = Field(..., max_length=50, description="修改人")
    version: int = Field(..., description="乐观锁版本号")


class AIWebSceneResponse(BaseModel):
    """场景响应模型"""
    model_config = ConfigDict(from_attributes=True)

    scene_id: str
    scene_name: str
    description: Optional[str]
    parent_id: Optional[str]
    node_path: Optional[str]
    node_level: int = Field(default=0, description="节点层级，根节点为0")
    sort_order: int
    scene_status: SceneStatus
    creator: str
    create_time: datetime
    modifier: Optional[str]
    modify_time: Optional[datetime]
    version: int
    children: List['AIWebSceneResponse'] = Field(default_factory=list)


class AIWebSceneTreeResponse(BaseModel):
    """场景树响应模型"""
    total_count: int = Field(..., description="总节点数")
    max_depth: int = Field(..., description="最大深度")
    root_nodes: List[AIWebSceneResponse] = Field(..., description="根节点列表")


class AIWebSceneQueryParams(BaseModel):
    """场景查询参数"""
    scene_name: Optional[str] = Field(None, description="场景名称模糊查询")
    scene_status: Optional[SceneStatus] = Field(None, description="场景状态")
    parent_id: Optional[str] = Field(None, description="父节点ID")
    creator: Optional[str] = Field(None, description="创建人")
    include_children: bool = Field(default=True, description="是否包含子节点")
    max_depth: Optional[int] = Field(None, description="最大查询深度")
